var MyLinkedList = function () {
  // 设计一个带头结点的链表
  this.next = null;
  this.val = -1;
};

/** 
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function (index) {
  let p = this; // 指向头节点
  let temp = 0;
  while (temp <= index && p) {
    p = p.next;
    temp++;
  }
  if (p)
    return p.val;
  else
    return -1;
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function (val) {
  let obj = new MyLinkedList();
  obj.val = val;
  obj.next = this.next;
  this.next = obj;
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function (val) {
  let obj = new MyLinkedList();
  obj.val = val;
  let p = this;
  while (p.next) {
    p = p.next;
  }
  p.next = obj;
};

/** 
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function (index, val) {
  if (index > this.getLength()) return;
  let obj = new MyLinkedList();
  obj.val = val;
  let p = this;
  let temp = 0;
  while (temp < index && p.next) {
    temp++;
    p = p.next;
  }
  obj.next = p.next;
  p.next = obj;
};

/** 
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function (index) {
  let p = this;
  let temp = 0;
  if (index < 0) return;
  while (temp < index && p) {
    temp++;
    p = p.next;
  }
  if (p === null || p.next === null) return;
  p.next = p.next.next;
};
MyLinkedList.prototype.logAllNode = function () {
  let p = this;
  while (p.next) {
    console.log(p.next);
    p = p.next;
  }
}
MyLinkedList.prototype.getLength = function () {
  let temp = this;
  let l = 0;
  while (temp.next) {
    l++;
    temp = temp.next;
  }
  return l;
}
let obj = new MyLinkedList();
// obj.addAtHead(1)
// obj.addAtTail(3)
obj.addAtIndex(1, 0)
console.log(obj.get(0));
// obj.logAllNode()
console.log(obj);

